//
//  LPActivityDetailComiuncationListViewController.m
//  LovingPartyBuilding
//
//  Created by 刘应平 on 2017/6/7.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "LPActivityDetailComiuncationListViewController.h"
#import "LPActivityDetailCommiuncationDetailTableViewCell.h"
#import "ZJSendMessageView.h"
#import <IQKeyboardManager.h>
//openfire
#import "XMPPRoom.h"
#import "drrr.h"
#import "XMPPRoomCoreDataStorage.h"

//对方发送消息
#define CellID @"ZJLivingDetailTableViewCell.h"
//自己发送消息
#define CellID_self @"ZJLivingDetailSelfTableViewCell"
#import "ZJLivingDetailTableViewCell.h"
#import "ZJLivingDetailSelfTableViewCell.h"
@interface LPActivityDetailComiuncationListViewController ()<UITableViewDataSource,UITableViewDelegate,ZJSendMessageViewDelegate,CSGrowingTextViewDelegate>
/**  tableT  */

@property (strong, nonatomic) UITableView  *tableView;
/** scrollView */
@property (nonatomic, strong) UIScrollView *scrollView;
/**  数据  */
@property (strong, nonatomic) NSMutableArray  *dataSouce;
/** 消息视图  */
@property (strong, nonatomic) ZJSendMessageView *sendView;

/** 对话列表 */
@property (nonatomic, strong) NSArray *messageArray;
/** 房间id */
@property (nonatomic, strong) NSString *roomjid;


@end

@implementation LPActivityDetailComiuncationListViewController
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[DRRRManager sharedManager] signout];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
//    [manager setEnable:NO];
}


-(id)init{
    self=[super init];
    if (self){
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTalkNotification:) name:DRRRRefreshTalksNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineNotification:) name:DRRRManager_Online_Notification object:nil];
   
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.titlelabel.text = @"互动交流";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
    
    [self initOpenfire];
    
    [self layoutUI];
}

- (void)initOpenfire{
    
    [[DRRRManager sharedManager] signinWithUsername:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID password:@"111111" host:kXMPP_HOST isregister:NO];
    
}
//加入房间
-(void)gotoSelectedChatRoomWithPassword:(NSString*)password{
    //设置用户名字
    [DRRRManager sharedManager].username = [ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.USER_NAME;
    [[DRRRChatRoomManager sharedChatRoomManager] queryChatRoomInfo:self.roomjid];
    
    [[DRRRChatRoomManager sharedChatRoomManager] joinInChatRoom:self
     .roomjid withPassword:password];
}


#pragma mark - 键盘处理
/**  键盘处理  */
- (void)keyboardWillShow:(NSNotification *)notification {
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.scrollView.y = LP_TopHeight - curkeyBoardHeight;
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.scrollView.y = LP_TopHeight;
        
    }];
}


#pragma mark - 数据

#pragma mark - Notification
- (void)onlineNotification:(NSNotification*)notification{
    BOOL online=[notification.object boolValue];
    if (online) {//登录成功
        [self gotoSelectedChatRoomWithPassword:nil];
        [self reloadTable];
    }
}

-(void)refreshTalkNotification:(NSNotification*)notification{
    [self reloadTable];
}

-(void)reloadTable{
    
    self.dataSouce=[[[DRRRMessage sharedMessage] talksWithJid:self.roomjid] mutableCopy];
    if (self.dataSouce.count > 0) {
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouce.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
    }
    
    
    
}

#pragma mark - 界面
- (void)layoutUI{
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.tableView];
    self.sendView = [ZJSendMessageView new];
    self.sendView.delegate = self;
    [self.scrollView addSubview:self.sendView];
    
    self.sendView.sd_layout
    .bottomSpaceToView(self.scrollView, 0)
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .heightIs(49);
    
    self.sendView.growingTextView.placeholderLabel.text = @"请输入内容";
    self.sendView.growingTextView.placeholderLabel.textColor = [UIColor lightGrayColor];
    self.sendView.sender.backgroundColor = [UIColor themeColor];
    [self.sendView.sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    CGRect frame = self.sendView.growingTextView.frame;
    frame.size.width = [UIScreen zj_screenWith] - 110 * [UIScreen zj_screenWScale];
    self.sendView.growingTextView.frame = frame;
    CGRect button = self.sendView.sender.frame;
    button.size.width = 80 * [UIScreen zj_screenWScale];
    button.size.height = 35;
    self.sendView.frame = button;
    self.sendView.sender.titleLabel.font = [UIFont systemFontOfSize:17 * [UIScreen zj_textFontScale]];
    self.sendView.sender.layer.cornerRadius = 4;
    self.sendView.sender.layer.masksToBounds = YES;

    [self.view bringSubviewToFront:self.navigView];
}


#pragma mark - 私有方法


#pragma mark - 监听事件


#pragma mark - SendMessageDelegate
- (void)sendMessageWithView:(ZJSendMessageView *)view message:(NSString *)message{
    if (message.length > 0) {
        //发送消息
        [[DRRRMessage sharedMessage] sendMessage:message inChatRoom:self.roomjid];
    }
}
- (void)growingTextView:(CSGrowingTextView *)growingTextView willChangeHeight:(CGFloat)height{
    height = height > 34 ? height :34;
    CGFloat viewHeight = height + 15;
    
    self.sendView.sd_layout
    .bottomSpaceToView(self.scrollView, 0)
    .leftSpaceToView(self.scrollView, 0)
    .rightSpaceToView(self.scrollView, 0)
    .heightIs(viewHeight);
    
    [self.sendView updateLayout];
    
    
}

- (void)growingTextView:(CSGrowingTextView *)growingTextView didChangeHeight:(CGFloat)height{
    
    
}



#pragma mark - UITableViewDataSource,UITableViewDelegate
/**  返回组个数  */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
/**  返回cell个数  */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSouce.count;
}
/**  返回cell高度  */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DRRRMessageContent *model = self.dataSouce[indexPath.row];
    //    return model.height + 85 * [UIScreen zj_screenHScale];
    return model.cellHeigth;
}
/**  cell初始化  */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DRRRMessageContent * model = self.dataSouce[indexPath.row];
    if (![model.fromName isEqualToString:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.USER_NAME]) {//对方发送
        ZJLivingDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
        cell.model = model;
        return cell;
        
    }else{
        ZJLivingDetailSelfTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID_self];
        
        cell.model = model;
        return cell;
    }

}


#pragma mark - 懒加载
/**  初始化tableView  */
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - LP_TopHeight - 49) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor themeGrayColor];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[ZJLivingDetailTableViewCell class] forCellReuseIdentifier:CellID];
        [_tableView registerClass:[ZJLivingDetailSelfTableViewCell class] forCellReuseIdentifier:CellID_self];
    }
    return _tableView;
}

- (NSMutableArray *)dataSouce{
    if (!_dataSouce) {
        _dataSouce = [NSMutableArray array];
    }
    return _dataSouce;
}

- (NSString *)roomjid{
    if (_roomjid == nil){
        _roomjid = [NSString stringWithFormat:@"%@%@.%@",self.model.ID,kXMPP_SUBDOMAIN,kXMPP_DOMAIN];
        
    }
    return _roomjid;
    
}
- (UIScrollView *)scrollView{
    if (_scrollView == nil){
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight)];
        _scrollView.contentOffset = CGPointMake(0, 0);
        _scrollView.contentSize = CGSizeMake(_scrollView.width, _scrollView.height);
        _scrollView.contentOffset = CGPointMake(0, 0);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
//        _scrollView.scrollEnabled = NO;
        
    }
    return _scrollView;
}
@end
